package com.dxt.mqtt.pushcallback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dxt.common.AppConstant;
import com.dxt.common.HttpUtil;
import com.dxt.common.SpringUtil;
import com.dxt.dao.BusiLogDao;
import com.dxt.model.BusiLogBean;
import com.dxt.service.CacheManager;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * 发布消息的回调类
 *
 * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。
 * 每个客户机标识都需要一个回调实例。在此示例中，构造函数传递客户机标识以另存为实例数据。
 * 在回调中，将它用来标识已经启动了该回调的哪个实例。
 * 必须在回调类中实现三个方法：
 *
 *  public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
 *
 *  public void connectionLost(Throwable cause)在断开连接时调用。
 *
 *  public void deliveryComplete(MqttDeliveryToken token))
 *  接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。
 *  由 MqttClient.connect 激活此回调。
 *
 */
public class PushCallBack implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());

    private static CacheManager cacheManager;

    private static BusiLogDao busiLogDao;
    static {
        cacheManager = SpringUtil.getBean(CacheManager.class);
        busiLogDao = SpringUtil.getBean(BusiLogDao.class);
    }
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        System.out.println("连接断开，可以做重连");
    }

    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println(String.format("topic:[%s]",topic));
//        System.out.println(String.format("data:[$s]",message.toString()));
        String deviceId = "";
        String orderType = "";
        if(!topic.isEmpty()){
            deviceId = topic.substring(0,topic.indexOf("/"));
            orderType = topic.substring(topic.lastIndexOf("/")+1,topic.length()+0);
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put(AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_DEVICEID,deviceId);
        data.put(AppConstant.REQUEST_REPONSE_PARAM.PARAM_IN_ORDERTYPE,orderType);
        data.put("data",new String(message.getPayload()));
        String MQTTObject = JSON.toJSONString(data);
//        System.out.println(MQTTObject);
        BusiLogBean busiLogBean = new BusiLogBean();
        busiLogBean.setDeviceId(String.valueOf(deviceId));
        busiLogBean.setOriginalStr(MQTTObject);
        busiLogBean.setLogType(2);
        busiLogBean.setNewJson(MQTTObject);
        busiLogBean.setCreateDate(new Timestamp(System.currentTimeMillis()));
        busiLogDao.addBusiLog(busiLogBean);
        String id = busiLogBean.getId().toString();
        //调用消防系统接口，发送设备上报信息到消防系统
        String response = null;
        try {
            response = HttpUtil.getHttpPostResponse(cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_XF_HY_POST_URL),
                    "json", MQTTObject,
                    cacheManager.getSysConfigByCode(AppConstant.SYS_CONFIG_KEY.KEY_TOKEN));
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("response="+response);
        JSONObject jsonObj = null;

        if(StringUtils.isNotBlank(response)){
            jsonObj = JSON.parseObject(response);
        }
        //发送成功后，更新日志状态，为已发送
        if(!jsonObj.isEmpty()){
            try {
                String code = jsonObj.getString(AppConstant.REQUEST_REPONSE_PARAM.PARAM_OUT_CODE);
                if(StringUtils.isNotBlank(code) && AppConstant.REPONSE_CODE.SUCCESS_CODE.equals(code)){
                    BusiLogBean busiLogBean1 = new BusiLogBean();
                    busiLogBean1.setId(BigDecimal.valueOf(Long.valueOf(id)));
                    busiLogBean1.setDeviceId(String.valueOf(deviceId));
                    busiLogBean1.setDealType(1);
                    busiLogBean1.setDealDate(new Timestamp(System.currentTimeMillis()));
                    busiLogDao.modifyBusiLog(busiLogBean1);
                }else{
                    BusiLogBean busiLogBean2 = new BusiLogBean();
                    busiLogBean2.setDeviceId(String.valueOf(deviceId));
                    busiLogBean2.setId(BigDecimal.valueOf(Long.valueOf(id)));
                    busiLogBean2.setDealType(2);
                    busiLogBean2.setDealDate(new Timestamp(System.currentTimeMillis()));
                    busiLogDao.modifyBusiLog(busiLogBean2);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            logger.error("[%s],未得到正确相应",MQTTObject);
        }

        //发送失败，更新日志状态为失败，重新发送

        //重复完成后，更新日志状态，为已发送
    }
}
